<?php

namespace Modules\Cart\Http\Controllers\Client\V1;

use Illuminate\Http\Request;
use Illuminate\Routing\Controller;

use Modules\Cart\Entities\CartItem;

use Modules\Product\Entities\Sku;

use Validator;
use ThrowException;
use Auth;

class CartItemController extends Controller
{
    public function index(Request $req)
    {
        $rule = [
        ];

        Validator::make($req->all(), $rule)->fails() && ThrowException::BadRequest();

        $user = Auth::requireLoginUser();

        $options = $req->all();
        $options['with'] = ['sku.product'];
        $options['builder'] = $user->cart_items()->whereHas('sku');


        $options['only'] = [
            'id',
            'uuid',
            'sku_info' => 'sku',
            'total',
            'is_selected',
            'created_at'
        ];

        $list = CartItem::getList($options);

        $list->each(function ($item) {
            $sku = $item->sku;
            $item->sku_info = [
                'id' => $sku->id,
                'uuid' => $sku->uuid,
                'title' => $sku->title,
                'thumb' => $sku->thumb,
                'stock' => $sku->stock,
                'money_price' => $sku->getOriginalPrice('money'),
                'score_price' => $sku->getOriginalPrice('score'),
                'discount_money_price' => $sku->getDiscountPrice('money'),
                'discount_score_price' => $sku->getDiscountPrice('score'),
                'attrs' => $sku->attrs,
                'product' => [
                    'id' => $sku->product->id,
                    'uuid' => $sku->product->uuid,
                    'number' => $sku->product->number
                ]
            ];

            $item->is_selected = time() - strtotime($item->updated_at) > 600 ? 0 : 1;
        });

        return $list->generateListResponse();
    }

    public function update(Request $req, $uuid)
    {
        $rule = [
            'total' => ['required']
        ];

        Validator::make($req->all(), $rule)->fails() && ThrowException::BadRequest();

        $user = Auth::requireLoginUser();

        $item = $user->cart_items()->where('uuid', $uuid)->first();

        if ($item) {
            $item->total = $req->total;
            $item->save();
        }

        return [];
    }

    public function store(Request $req)
    {
        $rule = [
            'sku_id' => ['required'],
            'total' => ['required']
        ];

        Validator::make($req->all(), $rule)->fails() && ThrowException::BadRequest();

        $user = Auth::requireLoginUser();

        $sku = Sku::getEntity([
            'id' => $req->sku_id
        ]);

        $item = $user->cart_items()->where('sku_id', $req->sku_id)->first();

        if ($item) {
            $item->total += $req->total;
            $item->save();
        }
        else {
            CartItem::create([
                'user_id' => $user->id,
                'sku_id' => $req->sku_id,
                'total' => $req->total,
                'product_type' => 'product',
                'product_id' => $sku->product_id,
                'money_price' => $sku->getOriginalPrice('money'),
                'score_price' => $sku->getOriginalPrice('score'),
            ]);
        }

        return [];
    }

    public function destroy(Request $req, $uuid)
    {
        $user = Auth::requireLoginUser();
        $item = $user->cart_items()->where('uuid', $uuid)->first();

        if ($item)
            $item->delete();
        else
            \Log::error('删除不存在的购物车条目');

        return [];
    }
}
